﻿using FireChat.Client.Model.Message.Concrete;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace FireChat.Client.Model.Message.Util;




public class MessageChianJsonConvert : JsonConverter<MessageChain>
{
    public override MessageChain? ReadJson(JsonReader reader, Type objectType, MessageChain? existingValue, bool hasExistingValue, JsonSerializer serializer)
    {

        if (reader.TokenType != JsonToken.StartArray) return new();

        MessageChain chain = new();
        var array = JArray.Load(reader);

        foreach (var item in array)
        {
            var type = item["Type"]?.ToObject<MessageType>();
            if (type == null) continue;

            switch (type)
            {
                case MessageType.Text:
                    chain.Add(item.ToObject<TextMessage>(serializer)); break;
                case MessageType.Image:
                    chain.Add(item.ToObject<ImageMessage>(serializer)); break;
            }
        }

        return chain;
    }

    public override void WriteJson(JsonWriter writer, MessageChain? value, JsonSerializer serializer)
    {
        writer.WriteStartArray();

        foreach (var message in value)
        {
            serializer.Serialize(writer, message);
        }

        writer.WriteEndArray();
    }
}
